<?php

namespace addons\csmitsm\library\xcore\xcflow\base;

use addons\csmitsm\library\xcore\xcflow\utils\XcflowallformUtils;
use Exception;
use app\common\library\Upload;
use addons\csmitsm\library\xcore\xcore\base\XcABackend;
use addons\csmitsm\library\xcore\xcore\utils\XcDaoUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcRequestUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcDatabaseUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcResponseUtils;
use addons\csmitsm\library\xcore\xcflow\utils\XcformDataUtils;
use addons\csmitsm\library\xcore\xcflow\utils\XcformFieldsUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcTransactionUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcAdminSessionUtils;

abstract class XcformADataCrudBackend extends XcABackend
{
    protected $xcformDao = null;
    protected $xcformidFieldname = null;

    protected function _getCreateOrUpdateXcfieldjsonObj($xcform_id, &$xcformFields, $xcformdata)
    {
        // createOrUpdate_view use xcflow_config
        $results = [];
        foreach ($xcformFields as &$field) {
            if (isset($field['fieldjsonObj']['xcform_prop_hidden']['value']) && $field['fieldjsonObj']['xcform_prop_hidden']['value'] == false) {
                $results[] = $field;
            }
        }
        return $results;
    }
    protected function _getShowXcformPageShowXcfieldjsonObj($xcform_id, &$xcformFields, $xcformdata)
    {
        // createOrUpdate_view use xcflow_config
        $results = [];
        foreach ($xcformFields as &$field) {
            if (!isset($field['fieldjsonObj']['xcform_prop_hidden']['value']) || $field['fieldjsonObj']['xcform_prop_hidden']['value'] == false) {
                $results[] = $field;
            }
        }
        return $results;
    }
    protected function _getShowXcformPageEditXcfieldjsonObj($xcform_id, &$xcformFields, $xcformdata){
        return [];
    }

    public function createOrUpdateXcformPage()
    {
        $id = XcRequestUtils::get("id");
        $xcform_id = XcRequestUtils::get("xcform_id", true);

        $xcform = XcDaoUtils::getRowById($this->xcformDao, $xcform_id);
        $xccontrol = "xcform";

        // fieldfulljson = xcfieldjson + field_value
        $xcformdata = null;
        $fieldfulljson = null;
        if (true) {
            $xcfieldjsonObj = XcformFieldsUtils::getXcfieldjsonJsonObjectFromXcform($xcform);

            $xcformdata = null;
            if (!empty($id)) {
                $xcformdata = XcformDataUtils::getPagedataByTablenameAndRowid($xcform->publishtablename,  $xcfieldjsonObj, $id);
            }

            $currentPageXcfieldjsonObj = $this->_getCreateOrUpdateXcfieldjsonObj($xcform_id, $xcfieldjsonObj, $xcformdata);
            $currentPageXcfieldfulljson = XcformFieldsUtils::getXcfullfieldjsonObjFromXcformdataAndXcformdata($currentPageXcfieldjsonObj, $xcformdata);
        }


        $xcfieldtags = XcformFieldsUtils::getAllXcfieldtags($xccontrol);

        $this->assignconfig("id", $id);
        $this->assignconfig("xcform", $xcform);
        $this->assignconfig("fieldfulljson", $currentPageXcfieldfulljson);
        $this->assignconfig("xcfieldtags", $xcfieldtags);
        $this->view->assign("xcfieldtags", $xcfieldtags);
        $this->assignconfig("controlPath", $this->getControlPath());
        $this->view->assign("xccontrol", $xccontrol);
        $this->view->assign("include_files",[]);        

        $result = XcTransactionUtils::service(function () use ($xcformdata) {
            return $this->_createOrUpdateXcformPage($xcformdata);
        });
        if ($result === true) {
            return $this->view->fetch();
        }
    }



    protected function _createOrUpdateXcformPage($xcformData)
    {
        return true;
    }

    public function createOrUpdateXcformSaveAjax()
    {
        $id = XcRequestUtils::post("id");
        $xcform_id = XcRequestUtils::post('xcform_id', true);
        $params = $this->request->post('row/a');

        [$result, $id] = XcTransactionUtils::service(function () use ($id, $xcform_id, $params) {
            $xcform = XcDaoUtils::getRowById($this->xcformDao, $xcform_id);
            $xcfieldjsonObj = XcformFieldsUtils::getXcfieldjsonJsonObjectFromXcform($xcform);
            $currentPageXcfieldjsonObj = $this->_getCreateOrUpdateXcfieldjsonObj($xcform_id, $xcfieldjsonObj, $params);

            $publishtablename = $xcform->publishtablename;
            $fieldjson['status'] = "draft";

            $xcformdata = null;
            if (empty($id)) {
                $params['admin_id'] = XcAdminSessionUtils::getUserId();
                $xcformdata = XcformDataUtils::createData($publishtablename, $currentPageXcfieldjsonObj, $params);
                $id = $xcformdata['id'];
            } else {
                $xcformdata = XcformDataUtils::updateData($publishtablename, $currentPageXcfieldjsonObj, $id, $params);
                $id = $xcformdata['id'];
            }

            return [$this->_createOrUpdateXcformSaveAjax($xcformdata), $id];
        });

        if ($result === true) {
            $this->success("保存成功", null, ["id" => $id]);
        }
    }

    public function createOrUpdateXcformSubmitAjax()
    {
        $id = XcRequestUtils::post("id");
        $xcform_id = XcRequestUtils::post('xcform_id', true);
        $params = $this->request->post('row/a');

        [$result, $id] = XcTransactionUtils::service(function () use ($id, $xcform_id, $params) {
            $xcform = XcDaoUtils::getRowById($this->xcformDao, $xcform_id);
            $xcfieldjsonObj = XcformFieldsUtils::getXcfieldjsonJsonObjectFromXcform($xcform);
            $publishtablename = $xcform->publishtablename;

            $fieldjson['status'] = "normal";

            $xcformdata = null;
            if (empty($id)) {
                $params['admin_id'] = XcAdminSessionUtils::getUserId();
                XcformFieldsUtils::processSpecialXcfieldParamsWhilteSumit($xcform, null, $params);
                $xcformdata = XcformDataUtils::createData($publishtablename, $xcfieldjsonObj, $params);
                $id = $xcformdata['id'];
            } else {
                XcformFieldsUtils::processSpecialXcfieldParamsWhilteSumit($xcform, $id, $params);
                $xcformdata = XcformDataUtils::updateData($publishtablename, $xcfieldjsonObj, $id, $params);
                $id = $xcformdata['id'];
            }

            return [$this->_createOrUpdateXcformSubmitAjax($xcformdata), $id];
        });
        if ($result === true) {
            $this->success("提交成功", null, ["id" => $id]);
        }
    }


    protected function _createOrUpdateXcformSaveAjax($xcformdata)
    {
        return true;
    }
    protected function _createOrUpdateXcformSubmitAjax($xcformdata)
    {
        return true;
    }

    public function showXcformPage()
    {
        $id = XcRequestUtils::get(["id", "ids"], true);
        $xcform_id = XcRequestUtils::get('xcform_id', true);
        $display_createbutton = XcRequestUtils::get("display_createbutton", false, "N");
        $xcform = XcDaoUtils::getRowById($this->xcformDao, $xcform_id);
        $xccontrol = "xcform";

        $fieldfulljson = null;
        if (true) {
            $xcfieldjsonObj = XcformFieldsUtils::getXcfieldjsonJsonObjectFromXcform($xcform);
            $xcformdata = XcformDataUtils::getPagedataByTablenameAndRowid($xcform->publishtablename, $xcfieldjsonObj, $id);
            if ($xcformdata['status'] == "draft") {
                XcResponseUtils::redirect("createOrUpdateXcformPage?xcform_id={$xcform_id}&id={$id}");
            }

            $showXcfieldjsonObj = $this->_getShowXcformPageShowXcfieldjsonObj($xcform_id, $xcfieldjsonObj, $xcformdata);
            $showXcfieldfulljson = XcformFieldsUtils::getXcfullfieldjsonObjFromXcformdataAndXcformdata($showXcfieldjsonObj, $xcformdata);

            $editXcfieldjsonObj = $this->_getShowXcformPageEditXcfieldjsonObj($xcform_id, $xcfieldjsonObj, $xcformdata);
            $editXcfieldfulljson = XcformFieldsUtils::getXcfullfieldjsonObjFromXcformdataAndXcformdata($editXcfieldjsonObj, $xcformdata);
        }
 

        $xcfieldtags = XcformFieldsUtils::getAllXcfieldtags($xccontrol);

        $this->assignconfig("id", $id);
        $this->assignconfig("xcform", $xcform);
        $this->assignconfig("fieldfulljson", $showXcfieldfulljson);
        $this->assignconfig("editXcfieldfulljson", $editXcfieldfulljson);
        $this->assignconfig("xcfieldtags", $xcfieldtags);
        $this->view->assign("xcfieldtags", $xcfieldtags);
        $this->assignconfig("controlPath", $this->getControlPath());
        $this->assignconfig("display_createbutton", $display_createbutton);
        $this->view->assign("xccontrol", $xccontrol);
        $this->view->assign("include_files",[]);

        $result = $this->_showXcformPage($xcformdata);
        if ($result === true) {
            return $this->view->fetch();
        }
    }

    protected function _showXcformPage($xcformdata)
    {
        return true;
    }


    public function queryRelateSubTableFieldsAndDatasByFieldcode()
    {
        $id = XcRequestUtils::get("id");
        $xcform_id = XcRequestUtils::get("xcform_id", true);
        $fieldcode = XcRequestUtils::get("fieldcode", true);
        $xcform = XcDaoUtils::getRowById($this->xcformDao, $xcform_id);
        $targetField = XcformFieldsUtils::getXcfieldjsonJsonItemFromXcformByFieldcode($xcform, $fieldcode);

        $subTablename = $targetField['fieldjsonObj']['xcform_base_property_input_subtable']['tablename'];
        $subShowfields = $targetField['fieldjsonObj']['xcform_base_property_input_subtable']['showfields'];
        $subTableForginfieldcode = $targetField['fieldjsonObj']['xcform_base_property_input_subtable']['subtableForginfieldcode'];

        $subXcform = XcflowallformUtils::getXcformByTablename($subTablename);
        $subXcfieldjsonObj = XcformFieldsUtils::getXcfieldjsonJsonObjectFromXcform($subXcform);

        $list = [];
        if (!empty($id)) {
            $datalist = XcDatabaseUtils::getListBySql($subTablename, [
                [$subTableForginfieldcode, '=', $id]
            ], $subShowfields, 'weigh asc');

            foreach ($datalist as $data) {
                $xcfullfieldjsonObj = XcformFieldsUtils::getXcfullfieldjsonObjFromXcformdataAndXcformdata($subXcfieldjsonObj, $data);
                foreach ($xcfullfieldjsonObj as &$item) {
                    $item['fieldtitle'] = null;
                }
                $list[] = $xcfullfieldjsonObj;
            }
        }

        $this->success(null, null, ["xcfieldjsonObj" => $subXcfieldjsonObj, 'list' => $list]);
    }

    public function getTabledataRowByFieldcodeAndDataid()
    {
        $xcform_id = XcRequestUtils::get("xcform_id");
        $fieldcode = XcRequestUtils::get("fieldcode");
        $data_id = XcRequestUtils::get("data_id");

        $xcform = XcDaoUtils::getRowById($this->xcformDao, $xcform_id);
        $targetField = XcformFieldsUtils::getXcfieldjsonJsonItemFromXcformByFieldcode($xcform, $fieldcode);

        $tablename = $targetField['fieldjsonObj']['xcform_base_selecttablefield']['tablename'];

        $row = XcDatabaseUtils::getRowById($tablename, $data_id);

        $this->success(null, null, ['row' => $row]);
    }

    public function queryTabledataListByFieldcode()
    {
        $xcform_id = XcRequestUtils::get("xcform_id");
        $fieldcode = XcRequestUtils::get("fieldcode");
        $pageNumber = XcRequestUtils::get("pageNumber");
        $filtervalue = XcRequestUtils::get("filtervalue");

        $xcform = XcDaoUtils::getRowById($this->xcformDao, $xcform_id);
        $targetField = XcformFieldsUtils::getXcfieldjsonJsonItemFromXcformByFieldcode($xcform, $fieldcode);

        $tablename = $targetField['fieldjsonObj']['xcform_base_selecttablefield']['tablename'];
        $filterfields = implode(',', $targetField['fieldjsonObj']['xcform_base_selecttablefield']['filterfields']);

        $showfields = null;
        if (true) {
            $showFieldArray = $targetField['fieldjsonObj']['xcform_base_selecttablefield']['showfields'];
            if (!in_array("id", $showFieldArray)) {
                $showFieldArray[] = "id";
            }
            $showfields = implode(',', $showFieldArray);
        }

        $result = XcDatabaseUtils::queryTabledataList($tablename, $showfields, $filterfields, $filtervalue, $pageNumber, 6);

        $this->success(null, null, $result);
    }


    public function upload()
    {
        $attachment = null;
        //默认普通上传文件
        $file = $this->request->file('file');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload();
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $row = XcDaoUtils::getRowBySql(new \app\common\model\Attachment(), [
            ['url', '=', $attachment->url]
        ], null, false, true);

        return json(['id' => $row->id, 'name' => $attachment->filename, 'url' => cdnurl($attachment->url, true)]);
    }


    public function del($ids = null)
    {
        $id = $ids;
        $xcform_id = XcRequestUtils::get("xcform_id", true);

        $xcform = XcDaoUtils::getRowById($this->xcformDao, $xcform_id);

        XcformDataUtils::deleteData($xcform->publishtablename, $id);

        $this->success();
    }
}
